#include<vector>
using std::vector;


class Solution {
public:
    int findUnsortedSubarray(vector<int>& nums) {
        if (nums.size() < 2) return 0;
        int n = nums.size();
        int minVal = nums[n-1], lastMinIdx = n-1;
        int maxVal = nums[0], lastMaxIdx = 0;
        for (int i = n-2; i >= 0; i--) {
            if (nums[i] > minVal) lastMinIdx = i;
            else minVal = nums[i];
        }
        if (lastMinIdx == n-1) return 0;

        for (int i = 0; i < n; i++) {
            if (nums[i] < maxVal) lastMaxIdx = i;
            else maxVal = nums[i];
        }
        return lastMaxIdx - lastMinIdx + 1;
        

    }
};